﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using HtmlAgilityPack;

namespace CommonAppSS
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new RestClient("https://apply.commonapp.org/");
            client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)";

            HtmlDocument htmlDoc = new HtmlDocument();
            string RequestVarificationToken = "";

            var request = new RestRequest("login", Method.GET);
            IRestResponse response = client.Execute(request);

            htmlDoc.LoadHtml(response.Content);

            var root = htmlDoc.DocumentNode;

            if (htmlDoc.DocumentNode != null)
            {
                var inputTags = root.Descendants("input");         
                if (inputTags != null)
                {
                    foreach (var inputTag in inputTags)
                    {
                        if (inputTag.HasAttributes)
                        {
                            string nameAttribute = inputTag.GetAttributeValue("name", "");
                            if (nameAttribute == "__RequestVerificationToken")
                            {
                                RequestVarificationToken = inputTag.Attributes["value"].Value;
                                Console.WriteLine("Request Token: {0}", RequestVarificationToken);
                            }
                        }
                    }
                }
            }

            if (RequestVarificationToken == "")
                return;

            var client2 = new RestClient("https://apply.commonapp.org/");
            client2.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)";

            var login = new RestRequest("login", Method.POST);

            login.AddParameter("UserName", "yipeng.wang.99@outlook.com");
            login.AddParameter("Password", "Lunet!990108");
            login.AddParameter("__RequestVerificationToken", RequestVarificationToken);

            login.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            login.AddCookie("__RequestVerificationToken", RequestVarificationToken);

            IRestResponse response2 = client2.Execute(login);

            // Console.WriteLine(response.Request);
            
            if (response2.Content.Contains("Login was unsuccessful"))
            {
                Console.WriteLine("Login Unsuccessful");
                Console.ReadLine();
                return;
            }
            else
                Console.WriteLine("Login Successful");

            // HtmlDocument htmlDoc2 = new HtmlDocument();
            // htmlDoc.LoadHtml(response2.Content);

            Console.WriteLine(response2.Content);
            Console.ReadLine();
        }
    }
}
